package com.ajk.server.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ajk.server.controller.access.ArgIndexForPrintLog;
import com.ajk.server.controller.events.RemoteSyncEvent;
import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.EaseUser;
import com.ajk.server.model.Suggest;
import com.ajk.server.model.request.UserReq;
import com.ajk.server.model.response.Result;
import com.ajk.server.model.response.ResultList;
import com.ajk.server.model.response.ResultObject;
import com.ajk.server.model.response.UserRes;
import com.ajk.server.security.AjkUserDetails;
import com.ajk.server.service.SuggestService;
import com.ajk.server.service.UsersService;
import com.ajk.server.utils.AjkUtil;
import com.ajk.server.utils.FileStoreUtil;
import com.ajk.server.utils.SpringContextUtil;
import com.ajk.shop.model.response.SimpleUserProfileRes;

@RestController
@RequestMapping("/users")
public class UserController {

	@Autowired
	UsersService usersService;

	@Autowired
	SuggestService suggestService;

	/**
	 * 根据userIds 获取 头像，用户名，id
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/find_simple_profile/by_ease_usernames", method = RequestMethod.POST)
	public ResultList<SimpleUserProfileRes> findSimpleUserProfile(@RequestBody String[] userId){
		List<SimpleUserProfileRes> list= null;
		if (ArrayUtils.isNotEmpty(userId)) {
			List<Integer> userIds = new ArrayList<Integer>();
			for (String string : userId) {
				userIds.add(Integer.parseInt(string));
			}
			list= usersService.findSimpleUsersByIds(userIds);
		}
		return new ResultList<>(list);
	}

	/**
	 *我的个人信息
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/profile", method = RequestMethod.GET)
	public ResultObject<UserRes> findMyProfile(Principal principal,Integer userId){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(userId != null && userId > 0){
			
		}else if(null != user){
			userId =  Integer.parseInt(principal.getName());
		}else{
			throw new AjkException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		UserRes userRes = usersService.findUsersById(userId);
		return new ResultObject<>(userRes);
	}

	/**
	 *用户修改个人信息
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/profile", method = RequestMethod.PUT)
	public Result updateMyProfile(@RequestBody UserReq myProfile,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new AjkException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		myProfile.setId(userId);
		myProfile.setAvatar(null); //不修改头像
		usersService.updateUsers(myProfile);
		
		RemoteSyncEvent event = new RemoteSyncEvent(userId, RemoteSyncEvent.SYNC_USER);
		SpringContextUtil.getApplicationContext().publishEvent(event);
		
		return new Result();
	}

	/**
	 *用户修改头像
	 */
	@ArgIndexForPrintLog(indexes={1})
	@RequestMapping(value = "/avatar", method = RequestMethod.POST,consumes="multipart/form-data")
	public Result updateAvatar(MultipartFile avatarFile,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new AjkException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		if(avatarFile!=null && avatarFile.getSize()>0){
			if (avatarFile.getSize() > 2097152) {
				throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "头像太大,请选择小于2兆的头像上传");
			}
			String fileDbName = FileStoreUtil.storeFile(avatarFile, "avatar");
			UserReq users = new UserReq();
			users.setId(userId);
			users.setAvatar(fileDbName);
			usersService.updateUsers(users);
			
			RemoteSyncEvent event = new RemoteSyncEvent(userId, RemoteSyncEvent.SYNC_USER);
			SpringContextUtil.getApplicationContext().publishEvent(event);
		} else {
			// 文件传输失败。抛异常
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "头像传输失败！请重试");
		}
		return new Result();
	}



	/**
	 * 健康档案-最近一次测量
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/patient_event/last_records", method = RequestMethod.GET)
	public ResultObject<EaseUser> findMyLastPatientEventRecords(Principal principal){
		Integer userId = Integer.parseInt(principal.getName());
		return null;
	}


	/**
	 *意见反馈
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/suggest", method = RequestMethod.POST)
	public ResultObject<Integer> suggest(@RequestBody Suggest suggest,Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new AjkException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		suggest.setUserId(userId);
		Integer id = suggestService.insertSuggest(suggest);
		return new ResultObject<>(id);
	}
	
	/**
	 * 健康档案-最近一次测量
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/qrcode", method = RequestMethod.GET)
	public ResultObject<String> qrcode(Principal principal){
		AjkUserDetails user = AjkUtil.getUserDetails(principal);
		if(null == user){
			throw new AjkException(ErrorConstant.ACCOUNT_NOT_LOGIN.getErrorCode(), "未登录,请先登录");
		}
		Integer userId = Integer.parseInt(principal.getName());
		String qrcode = usersService.getQRcode(userId);
		return new ResultObject<>(qrcode);
	}
	
}
